package cn.fjc920.siaa.fragments

import android.annotation.SuppressLint
import android.hardware.biometrics.BiometricManager.Strings
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.viewpager.widget.ViewPager
import cn.fjc920.siaa.R
import cn.fjc920.siaa.activitys.AddActivity
import cn.fjc920.siaa.activitys.FilterActivity
import cn.fjc920.siaa.activitys.HomePageActivity
import com.google.android.material.tabs.TabLayout
import kotlinx.android.synthetic.main.fragment_home.view.*

class HomeFragment :Fragment() {

    companion object {
        @SuppressLint("StaticFieldLeak")
        lateinit var homeTodayFragment: HomeTodayFragment
        @SuppressLint("StaticFieldLeak")
        lateinit var homeAllFragment: HomeAllFragment
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        val view = inflater.inflate(R.layout.fragment_home, container, false)
        val activity = activity as HomePageActivity
        init(activity.supportFragmentManager,view)
        initClick(activity,view)
        return view
    }

    private fun initClick(activity: HomePageActivity, view: View) {

        view.tv_filter.setOnClickListener {
            FilterActivity.actionStart(activity)
        }

        view.btn_actionAdd.setOnClickListener {
            AddActivity.actionStart(activity,"添加工时",null,null)
        }

    }

    private fun init(fm: FragmentManager, view:View) {

        homeTodayFragment = HomeTodayFragment()
        homeAllFragment = HomeAllFragment()
        val viewpager: ViewPager = view.findViewById(R.id.home_viewPager)
        //fragment缓存
        viewpager.offscreenPageLimit = 2
        viewpager.adapter = MyAdapter(fm,homeTodayFragment,homeAllFragment)
        val tabLayout:TabLayout = view.findViewById(R.id.home_tab_Layout)
        tabLayout.setupWithViewPager(viewpager)
    }

    internal class MyAdapter(fm: FragmentManager?,val homeTodayFragment: HomeTodayFragment,val homeAllFragment: HomeAllFragment) :
        FragmentStatePagerAdapter(fm!!, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {

        // Return Fragment to display for that page
        override fun getItem(position: Int): Fragment {
            return when (position) {
                0 -> homeTodayFragment
                1 -> homeAllFragment
                else -> Fragment()
            }
        }

        // will be displayed as the tab's label
        override fun getPageTitle(position: Int): CharSequence? {
            return when (position) {
                0 -> "今日"
                1 -> "全部"
                else -> null
            }
        }

        override fun getCount(): Int {
            return 2
        }
    }
}